/**
 * Copyright 2008 Mathias Doenitz, http://lis.to/
 *
 * This file is part of the lis.to java desktop client. The lis.to java desktop client is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * The lis.to java desktop client is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with the lis.to java desktop client.
 * If not, see http://www.gnu.org/licenses/
 */

package listo.utils.types;

public class KeyValuePair<K, V> implements Comparable<KeyValuePair<K, V>> {

    private final K key;
    private V value;

    public KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }

    public V setValue(V value) {
        V oldValue = this.value;
        this.value = value;
        return oldValue;
    }

    @SuppressWarnings({"unchecked"})
    public int compareTo(KeyValuePair<K, V> kvp) {
        if (!(key instanceof Comparable) || !(kvp.getKey() instanceof Comparable)) {
            throw new RuntimeException("Key not comparable");
        }

        return ((Comparable<K>) key).compareTo(kvp.getKey());
    }

    public boolean equals(Object kvp) {
        if (!(kvp instanceof KeyValuePair)) return false;
        KeyValuePair otherKVP = (KeyValuePair) kvp;
        return eq(key, otherKVP.getKey()) && eq(value, otherKVP.getValue());
    }

    private static boolean eq(Object o1, Object o2) {
        return o1 == null ? o2 == null : o1.equals(o2);
    }

    public int hashCode() {
        return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
    }

    public String toString() {
        return key + "=" + value;
    }

}
